<?php

class AccountController extends Zend_Controller_Action {

    protected $account;

    public function init() {
        $this->account = new Application_Model_DbTable_Account();

        if ($this->_helper->FlashMessenger->hasMessages()) {

            $this->view->messages = $this->_helper->FlashMessenger->getMessages();
        }
    }

    public function indexAction() {
        // action body
    }

    public function confirmAction() {

        $key = $this->_request->getParam('key');

        // Key should not be blank
        if ($key != "") {

            $this->view->pageTitle = "Confirm your eMail";

            $accountTable = new Application_Model_DbTable_Account();
            $query = $seiteTable->select();
            $query->from('account', array('id'));
            $query->where('recovery = ?', $key);
            $account = $accountTable->fetchRow($query);
            $this->view->inhalt = $about->inhalt;

            if ($account) {

                // Account found, so confirm it and reset the recovery attribute
                $account->setConfirmed(1);
                $account->setRecovery("");

                // Save the account to the database
                $em->persist($account);
                $em->flush();

                // Set the flash message and redirect the user to the login page
                $this->_helper->flashMessenger->addMessage(
                        Zend_Registry::get('config')->messages->register->confirm->successful
                );
                $this->_helper->redirector('login', 'account');
            } else {

                // Set the flash message and redirect the user to the login page
                $this->_helper->flashMessenger->addMessage(
                        Zend_Registry::get('config')->messages->register->confirm->failed
                );
                $this->_helper->redirector('login', 'account');
            }
        }
    }

    public function loginAction() {

        $this->view->pageTitle = 'Login to Your Account';

        $form = new Application_Model_FormLogin(array('action' => '/account/login'));
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->_request->getPost())) {

                $username = $form->getValue('username');
                $password = $form->getValue('password');


                $this->_helper->flashMessenger->addMessage('You are logged in');
                $this->_helper->redirector('Index', 'index');
            }
        }
        $this->view->form = $form;
    }

    public function lookup($username, $email) {
        // TODO
        return "";
    }

    public function registerAction() {

        $this->view->pageTitle = 'Create your Account';

        $form = new Application_Model_FormRegister(array('action' => '/account/register'));

        if ($this->getRequest()->isPost()) {

            if ($form->isValid($this->_request->getPost())) {

                $account = ""; // lookup($form->getValue('username'), $form->getValue('email'));


                if (!$account) {

                    /*
                      // Assign the account attributes
                      $account->setUsername($form->getValue('username'));
                      $account->setVorname($form->getValue('vorrname'));
                      $account->setNachname($form->getValue('nachname'));
                      $account->setGeschlecht($form->getValue('geschlecht'));
                      $account->setEmail($form->getValue('email'));
                      $account->setOeffentlich($form->getValue('oeffentlich'));
                      $account->setZip($form->getValue('zip'));
                      $account->setPassword($form->getValue('password'));
                      $account->setConfirmed(0);

                      $map = new GoogleMapAPI();
                      $coordinates = $map->getGeoCode($form->getValue('zip'));

                      $account->setLatitude($coordinates['lat']);
                      $account->setLongitude($coordinates['lon']);


                      $account->setRecovery($this->_helper->generateID(32));
                     */
                    $newaccount = array(
                        'username' => $this->getRequest()->getParam('username'),
                        'plz' => $this->getRequest()->getParam('plz'),
                        'email' => $this->getRequest()->getParam('email'),
                        'password' => $this->getRequest()->getParam('password'),
                        'confirmed' => "0",
                        'recovery' => $this->genRandomString(32),
                        'created' => date('Y-m-d H:i:s', time())
                    );

                    try {


                        $this->account->insert($newaccount);
                        $mail = new Zend_Mail();
                        $mail->setFrom(Zend_Registry::get('config')->email->adress, Zend_Registry::get('config')->email->from);
                        $mail->addTo($newaccount["email"], "{$newaccount["username"]}");
                        $mail->setSubject('Dear ' . $newaccount["username"] . ' confirm your account');


                        include  '_email_confirm.phtml';
                        echo $email;
                        $mail->setBodyText($email);
                        $mail->send();
                        
                        $this->_helper->flashMessenger->addMessage('Check your mail, to complete your regestriation.');
                        $this->_helper->redirector('login', 'account');
                    } catch (Exception $e) {
                        $this->view->errors = array(array("There was a problem creating your account."));
                    }
                } else {

                    $this->view->errors = array(
                        array("The desired username {$form->getValue('username')} has already been taken, or
              the provided e-mail address is already associated with a registered user.")
                    );
                }
            } else {
                $this->view->errors = $form->getErrors();
            }
        }

        $this->view->form = $form;
    }

    function genRandomString($length = 12) {
        $characters = "0123456789abcdefghijklmnopqrstuvwxyz";
        $string = "";
        for ($p = 0; $p < $length; $p++) {
            $string .= $characters[mt_rand(0, strlen($characters) - 1)];
        }
        return $string;
    }

}

